package com.lgc.leetcode.easy.palindrome;

public class Program {
    public static void main(String[] args) {
        Program program = new Program();
        System.out.println(program.isPalindrome2(10));
        System.out.println(program.isPalindrome(232432));
        System.out.println(program.isPalindrome(2104320003));
        System.out.println(program.isPalindrome(2328232));
    }

    //反转求回文数
    public boolean isPalindrome(int x) {
        if (x < 0) {
            return false;
        }

        if (x == 0) {
            return true;
        }

        int newValue = 0;
        int pop = 0;
        int originValue = x;
        while (x > 0) {
            pop = x % 10;
            x = x / 10;

            if (newValue > Integer.MAX_VALUE / 10 || (newValue == Integer.MAX_VALUE / 10 && pop > 7)) {
                return false;
            }

            newValue = newValue * 10 + pop;
        }

        return originValue == newValue;
    }

    //为了避免数字反转可能导致的溢出问题，为什么不考虑只反转int 数字的一半？
    // 毕竟，如果该数字是回文，其后半部分反转后应该与原始数字的前半部分相同。
    public boolean isPalindrome2(int x) {
        if (x < 0 || (x % 10 == 0 && x != 0)) {
            return false;
        }

        if (x < 10) {
            return true;
        }

        int newValue = 0;
        int pop = 0;

        //反转int 数字的一半
        while (x > newValue) {
            pop = x % 10;
            newValue = newValue * 10 + pop;
            x = x / 10;
        }

        return x == newValue || x == newValue / 10;
    }
}
